/*
 * @Author: LiZhiJian
 * @Description: 为超声波避障准备
 * @Date: 2025-10-28 15:48:00
 * @LastEditTime: 2025-10-30 14:59:19
 * @Email: LiZhiJian8552@163.com
 */

#include "stm32f10x.h"
#include "timer.h"

extern uint16_t Time;
void Timer_Init(void){
    Time=0;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);

    // TIM2使用内部时钟,定时器将使用来自STM32内部时钟系统的时钟信号作为计数基准
    TIM_InternalClockConfig(TIM2);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct={0};
    TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
    TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
    TIM_TimeBaseInitStruct.TIM_Period=7200-1; //1e-4s=0.1ms
    TIM_TimeBaseInitStruct.TIM_Prescaler=0;
    // 重复计数
    TIM_TimeBaseInitStruct.TIM_RepetitionCounter=0;

    TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct);

    TIM_ClearFlag(TIM2,TIM_FLAG_Update);
    // 使能update中断
    TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);

    // 配置中断
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    NVIC_InitTypeDef NVIC_InitStruct={0};
    // 选择中断通道
    NVIC_InitStruct.NVIC_IRQChannel=TIM2_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=2;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;

    NVIC_Init(&NVIC_InitStruct);

    TIM_Cmd(TIM2,ENABLE);
}
void TIM2_IRQHandler(){
    if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET){
        if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_1)==1){
            Time++;
        }
        TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
    }
}
